"""
k线的时间是收盘时间还是开盘时间
如果是开盘时间的话:
  那么日线的收盘价 和小时线23点的收盘价应该一样
  日线的开盘价   和小时线0点的开盘价一样
"""
import pandas as pd
from utils import read_sql

for datasource in ["glassnode", "binance", "okx"]:
    df = read_sql(f"select * from k_line where symbol='BTC' and datasource = '{datasource}' order by datetime",
                  db_name="all_history_ohlcvm_coinmarketcap")
    if datasource == "okx":
        df = df[df["type"] == "spot"]
    df["date"] = df["datetime"].dt.date
    day_df = df[df["frequency"] == "1d"]
    hour_df = df[df["frequency"] == "1h"]
    count_ser = hour_df.groupby("date")["datetime"].count()
    choose_dates = count_ser[count_ser == 24].index.tolist()
    day_df = day_df[day_df["date"].isin(choose_dates)]
    hour_df = hour_df[hour_df["date"].isin(choose_dates)]
    # begin_date = max(day_df["date"].min(), hour_df["date"].min())
    # end_date = min(day_df["date"].max(), hour_df["date"].max())
    # day_df = day_df[(day_df["date"] >= begin_date) & (day_df["date"] <= end_date)]
    # hour_df = hour_df[(hour_df["date"] >= begin_date) &(hour_df["date"] <= end_date)]
    # df['timestamp'] = df['timestamp'].apply(
        # lambda x: x - datetime.timedelta(seconds=1))  # 时间记录的为0点，但是其实是统计的前一天的数据； 统一减去1秒，调整到昨天
    first_hour_df = hour_df[hour_df["datetime"].dt.hour == 0]
    last_hour_df = hour_df[hour_df["datetime"].dt.hour == 23]
    # first_hour_df = hour_df[hour_df['datetime'].apply(lamdba x : str(x)[11:16] == "00:00")]
    day_open = day_df.set_index("date")["open"]
    day_close = day_df.set_index("date")["close"]
    first_hour_open = first_hour_df.set_index("date")["open"]
    last_hour_close = last_hour_df.set_index("date")["close"]
    print(datasource)
    assert len(day_open) == len(first_hour_open)
    assert day_open.equals(first_hour_open), f"{datasource}不一样"
    assert len(day_close) == len(last_hour_close)
    assert day_close.equals(last_hour_close), f"{datasource}不一样"